#include <iostream>
#include <string.h>
#include "server.h"

// Forward declares
//
void usage();

// Display program usage
//
void usage()
{
    std::cout << "server [options]\n";
    std::cout << "Options:\n";
    std::cout << "  --help\t\tDisplay usage information\n";
    std::cout << "  -p [port]\t\tPort number; default 9000\n";
    
    exit(0);
}

// Main entry point
//
int main (int argc, char * const argv[]) 
{
    short port = kDefaultPort;
    
    // Process arguments to set the host name and port
    //
    for (int i = 1; i < argc; ++i)
    {
        if (strcmp("--help", argv[i]) == 0)
        {
            usage();
        }
        else if (strcmp("-p", argv[i]) == 0 && i + 1 < argc)
        {
            ++i;    // extra step
            port = (short) atoi(argv[i]);
        }
        else 
        {
            // Invalid parameters
            //
            usage();
        }
    }
    

    Server server(port);
    if (server.open())
    {
        std::cout << "Server initialized.\n";
        std::cout << "Port:\t" << port << "\n\n";
       
        bool isDone = false;
        while (!isDone)
        {
            
            isDone = server.wait();
        }
        
        std::cout << "Process ending.\n";
    }
    else 
    {
        std::cout << "Error initializing server.\n";
    }

    return 0;
}
